import {
  Component,
  ViewChild,
  EventEmitter,
  Input,
  Output
} from "@angular/core";
import {
  IonicPage,
  NavController,
  ModalController,
  ActionSheetController,
  ToastController,
  LoadingController,
  App
} from "ionic-angular";
import { Camera, CameraOptions } from "@ionic-native/camera";

import { SlidePhotoPage } from "./slide-photo/slide-photo";
// import { UploadApi } from "../../providers/api/upload";
import { BaseUI } from "../../common/baseUI";
import { TeamSeriveProvider } from "../../providers/team-serive/team-serive";
import { UploadApi } from "../../providers/api/upload";
@IonicPage()
@Component({
  selector: "camera",
  templateUrl: "camera.html"
})
export class CameraComponent extends BaseUI {
  @ViewChild("fileInput") fileInput;

  @Input() pictures: any = [];
  @Input() picturesFullPath: any = [];
  
  //以下3个变量评测不用管
  photonum: number = 9;
  bucketType = "UserBucket";
  useCropper: boolean = true;

  //上传完成之后触发父组件事件
  @Output() picked = new EventEmitter();
  @Output() deleted = new EventEmitter();

  len: number = 0;

  constructor(
    public navCtrl: NavController,
    public modalCtrl: ModalController,
    public actionSheetCtrl: ActionSheetController,
    private camera: Camera,
    // private uploadApi: UploadApi,
    public toastCtrl: ToastController,
    public showCtrl: LoadingController,
    public teamSeriveProvider: TeamSeriveProvider,
    private uploadApi: UploadApi,
    public app: App
  ) {
    super();
  }

  // 打开相机
  openCamera(sourceType = "CAMERA") {
    if (Camera["installed"]()) {
      const options: CameraOptions = {
        quality: 80,
        targetWidth: 900,
        targetHeight: 900,
        destinationType: this.camera.DestinationType.FILE_URI,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE,
        saveToPhotoAlbum: true,
        sourceType: this.camera.PictureSourceType[sourceType], //拍照时，此参数必须有，否则拍照之后报错，照片不能保存
        correctOrientation: true //Corrects Android orientation quirks
      };

      this.camera.getPicture(options).then(
        imageData => {
          // console.log('camera getPictures \n' + imageData)

          this.uploadPut([imageData]);
          this.camera.cleanup();
        },
        err => {
          if (err !== "No Image Selected") {
            super.showToast(this.toastCtrl, "拍照出错，请重试");
          }
          this.camera.cleanup();
        }
      );
    } else {
      //调用相册
      this.fileInput.nativeElement.click();
    }
  }

  //file选择完图片之后触发
  processWebImage(event) {
    let reader = new FileReader();
    let base64Gruop: any[] = [];

    reader.readAsDataURL(event.target.files[0]); //[0]input标签
    reader.onload = readerEvent => {
      // console.log(readerEvent);
      let imageData = (readerEvent.target as any).result; //图片的base64数据
      base64Gruop.push(imageData);

      // console.log(this.fileInput);
      // console.log(event.target.files);
      this.uploadPut(base64Gruop, event.target.files);

      // clear image input
      this.camera.cleanup();
    };
  }

  uploadPut(imageDatas, files?) {
    if (this.useCropper) {
      //调起模态窗 Cropper组件进行图片裁剪
      let profileModal = this.modalCtrl.create("CropperComponent", {
        cropperData: imageDatas,
        useRatio: false
      });
      //获取裁剪过的base64图片
      profileModal.onDidDismiss(data => {
      
        if (data && data.length > 0) {
          console.log(1); 
          
          this.uploadPic(data, (urls, fullPicPaths) => {
            this.uploadPicCB(urls, fullPicPaths);
          });
        }
      });
      profileModal.present();
    } else {
      this.uploadPic(
        imageDatas,
        (urls, fullPicPaths) => {
          this.uploadPicCB(urls, fullPicPaths);
        },
        files
      );
    }
  }

  uploadPicCB(urls, fullPicPaths) {
    this.pictures = this.pictures.concat(urls);
    this.picturesFullPath = this.picturesFullPath.concat(fullPicPaths);

    this.len = this.pictures.length;
    this.picked.emit({ 
      pictures: this.pictures,
      picturesFullPath: this.picturesFullPath
    });
  }

  //图片上传
  uploadPic(pics, callback, files?) {
    if (!pics || pics.length === 0) return;

    const loading = super.showLoading(this.showCtrl, "上传中");

    let tpics = [];
    let fullPicPaths = [];

    if (!files)
      files = this.fileInput.nativeElement
        ? this.fileInput.nativeElement.files || ""
        : "";
        this.removePhoto(0);
    //网值可能调用 相册 需要多张照片的同时上传 评测不需要
    for (let i = 0; i < pics.length; i++) {
      //评测只需要关注pics[i]
      this.uploadApi
        .uploadImage(pics[i], this.bucketType, null, files[i] || null)
        .then(res => {
          console.log(res);
          
          loading.dismiss();
          if (res.status == 200 && res.msg == "OK") {
            callback(res);
          } else if (res.status == 500) {
            super.showToast(this.toastCtrl, "登录失效，请重新登录");
            this.app.getRootNav().setRoot("LoginOrRegisterPage");
            return;
          } else {
            super.showToast(
              this.toastCtrl,
              "上传图片失败，请检查网络连接是否正常"
            );
          }
        })
        .catch(err => {
          super.showToast(this.toastCtrl, "图片上传失败");
          loading.dismiss();
        });
    }

    // clear image input
    this.fileInput.nativeElement.value = "";
  }

  // 打开弹窗
  select() {
    const actionSheet = this.actionSheetCtrl.create({
      cssClass: "headChoice",
      buttons: [
        {
          text: "拍照",
          // role: 'destructive',
          handler: () => {
            this.openCamera("CAMERA");
            // console.log('点击拍照');
          }
        },
        {
          text: "从相册选择",
          handler: () => {
            // this.choosePhoto(true, false);
            this.openCamera("PHOTOLIBRARY");
            // console.log('点击从相册选择');
          }
        }
      ]
    });
    actionSheet.present();
  }

  // 删除照片
  removePhoto(index) {
    const targetPicture = this.pictures[index];
    this.pictures.splice(index, 1);
    this.picturesFullPath.splice(index, 1); 
    this.len--;

    this.deleted.emit({
      targetPicture: targetPicture,
      index: index,
      pictures: this.pictures,
      picturesFullPath: this.picturesFullPath
    });
  }

  // 放大图片
  zoomImage(index) {
    this.navCtrl.push(SlidePhotoPage, {
      i: index,
      photo: this.pictures[0].data
    });
  }
}
